package com.lxyk.controller;

import com.lxyk.pojo.Admin;
import com.lxyk.service.AdminService;
import com.lxyk.utils.MailUtils;
import com.lxyk.utils.Sample;
import com.lxyk.utils.UUidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Random;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    /**
     * 注册功能
     * @param admin 对象 用户名 密码
     * @param repassword 确认密码
     * @param pagecode   页面验证码
     * @param session
     * @return
     */
    @RequestMapping("/register")
    public String registe(Admin admin, String repassword, String pagecode, HttpSession session){

        //1.校验验证码
        //1.1从session获得验证码
        String checkCode = (String) session.getAttribute("checkCode");
        session.removeAttribute("checkCode");//确保验证码一致性
        //1.2 判断比较
        if (checkCode.isEmpty() || pagecode.isEmpty() || !checkCode.equalsIgnoreCase(pagecode)){
            //如果不一致 跳转到注册页面 验证码错误
            session.setAttribute("msg","验证码错误");
            return "redirect:/register.jsp";
        }

        //2.校验两次密码是否一致
        //2.1校验是否有数据
        if (admin == null || admin.getUsername().isEmpty() || repassword.isEmpty()){
            session.setAttribute("msg","密码输入为空");
            return "redirect:/register.jsp";
        }

        //2.2 校验是否一致
        if (!repassword.equalsIgnoreCase(admin.getPassword())){
            session.setAttribute("msg","密码不一致");
            return "redirect:/register.jsp";
        }

        //3.校验用户名是否可用
        Integer integer = adminService.checkUserName(admin.getUsername());
        if (integer!=0){
            //用户名已存在 不可用 跳转到注册页面 提示：用户名已存在
            session.setAttribute("msg","用户名已存在");
            return "redirect:/register.jsp";
        }

        //4.注册，1.向数据库添加数据 2.跳转到登录界面
        //生成激活码 UUID：随机字符32位
        String uuid = UUidUtil.getUuid();
        admin.setCode(uuid);
        adminService.addAdmin(admin);

        //5.发激活邮件到邮箱中
        String email=admin.getEmail();
        String title="激活邮箱账号";
        String content="恭喜你完整注册，下一步激活账号:"+
                "<a href='http://localhost:8080/admin/setStatus?code="+uuid+"'>点击激活</a>";

        MailUtils.sendMail(email,content,title);
        return "redirect:/login.jsp";
    }

    @RequestMapping("/setStatus")
    public String setStatus(String code,HttpSession session){
        if (code == null || code == ""){
            session.setAttribute("msg","激活码错误");
            return "redirect:/login.jsp";
        }
        //1.查询激活码对应的账户
        Admin admin=adminService.findByCode(code);
        //2.结果为空 激活码错误或已经使用
        if (admin == null){
            session.setAttribute("msg","激活码错误或者已经使用");
            return "redirect:/login.jsp";
        }
        //3.不为空 将状态设为1 同时清空激活码
        admin.setStatus(1);
        admin.setCode(null);
        adminService.update(admin);
        session.setAttribute("msg","激活成功，请登录");
        return "redirect:/login.jsp";
    }

    @RequestMapping("/login")
    public String login(Admin admin,String pagecode,String phoneCode,HttpSession session){//其实我们可以只用手机验证码登录 不用用户名密码
        //1.校验验证码
        //1.1.session获取真正验证码
        String checkCode = (String) session.getAttribute("checkCode");
        session.removeAttribute("checkCode");

        //1.2判断
        if (checkCode == null || pagecode == null || checkCode.isEmpty() || pagecode.isEmpty() || !checkCode.equalsIgnoreCase(pagecode)){
            session.setAttribute("msg","验证码错误");
            return "redirect:/login.jsp";
        }
        //校验手机验证码
        String phoneCheckCode = (String) session.getAttribute(admin.getPhone());
        session.removeAttribute(admin.getPhone());
        if (phoneCheckCode == null || phoneCode == null || phoneCheckCode.isEmpty() || phoneCode.isEmpty() || !phoneCheckCode.equalsIgnoreCase(phoneCode)){
            session.setAttribute("msg","手机验证码错误");
            return "redirect:/login.jsp";
        }

        //2.判断用户名是否正确
        Admin login=adminService.login(admin);
        if (login == null){
            session.setAttribute("msg","用户名或密码错误");
            return "redirect:/login.jsp";
        }

        //不为空
        session.setAttribute("admin",login);
        return "redirect:/user/findByPage";
    }

    //发短信
    @RequestMapping("/sendMessage")
    @ResponseBody
    public String sendMessage(String phoneNum,HttpSession session) throws Exception {
        //生成验证码
        String code=getCheckCode();
        System.out.println("phoneNum"+phoneNum+""+code);
        //向手机发短信
        Sample.sendMessage(phoneNum,code);
        //向session保存
        session.setAttribute(phoneNum,code);
        return "OK";
    }

    private String getCheckCode() {
        String str="1234";
        int size=str.length();
        Random random = new Random();
        StringBuffer sb=new StringBuffer();
        for (int i = 1; i <=4 ; i++) {
            int index = random.nextInt(size);
            char c = str.charAt(index);
            sb.append(c);
        }
        return sb.toString();
    }
}
